var EXPORTED_SYMBOLS = [];

const { classes: Cc, interfaces: Ci } = Components;

Components.utils.import("resource://downloadextender/common.js");

/**
 * A very simple counter.
 */
downloadextender.number = {

  /* Current message count.  */
  _count : 0,

  /**
   * Returns the current message count.
   * @return the current message count.
   */
  get count() { return this._count; },

  /**
   * Increments the message count by one.
   */
  increment : function() {
    try {
      this._count++;
	}
	catch (e) { downloadextender.consoleService("increment: "+e); }
  }
},
downloadextender.pref = {
   //gets firstrun preference from branch  
   get firstrun() { 
     try {
       let _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.downloadextender.");
	   if (_prefs.getPrefType("firstrun")) { _prefs = _prefs.getBoolPref("firstrun"); }
	   else {
	     _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	     _prefs = _prefs.getBoolPref("firstrun");
	   }
       return _prefs;	
	 }
	 catch (e) { downloadextender.consoleService("firstrun: "+e); }
   },
   savefirstrun : function(boolenable) {
     try {
       let _prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
       _prefService.setBoolPref("extensions.downloadextender.listen", !boolenable);
	 }
	 catch (e) { downloadextender.consoleService("savefirstrun: "+e); }
   },
   //get listen preference
   get listen() { 
     try {
       let _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.downloadextender.");
	   //gets preference if preference key is present
	   if (_prefs.getPrefType("listen")) { _prefs = _prefs.getBoolPref("listen"); }
	   else {
	     //load default preference
	     _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	     _prefs = _prefs.getBoolPref("listen");
	   }
       return _prefs;	
	 }
	 catch (e) { downloadextender.consoleService("listen: "+e); }
   },
   get detectall() { 
     try {
       let _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.downloadextender.");
	   //gets preference if preference key is present
	   if (_prefs.getPrefType("detectall")) { _prefs = _prefs.getBoolPref("detectall"); }
	   else {
	     //load default preference
	     _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	     _prefs = _prefs.getBoolPref("detectall");
	   }
       return _prefs;	
	 }
	 catch (e) { downloadextender.consoleService("detectall: "+e); }
   },
   get displaytype() { 
     try {
       let _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.downloadextender.");
	   //gets preference if preference key is present
	   if (_prefs.getPrefType("displaytype")) { _prefs = _prefs.getCharPref("displaytype"); }
	   else {
	     //load default preference
	     _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	     _prefs = _prefs.getCharPref("displaytype");
	   }
       return _prefs;	
	 }
	 catch (e) { downloadextender.consoleService("detectall: "+e); }
   },
   savedetectall : function(boolenable) {
     try {
       let _prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
	   if (boolenable == "false") {
         _prefService.setBoolPref("extensions.downloadextender.detectall", false);
	   }
	   else {
	    _prefService.setBoolPref("extensions.downloadextender.detectall", true);
	   }
	 }
	 catch (e) { downloadextender.consoleService("savedetectall: "+e); }
   },   
   get blacklistenable() { 
     try {
       let _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.downloadextender.");
	   //gets preference if preference key is present
	   if (_prefs.getPrefType("blacklistenable")) { _prefs = _prefs.getBoolPref("blacklistenable"); }
	   else {
	     //load default preference
	     _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	     _prefs = _prefs.getBoolPref("blacklistenable");
	   }
       return _prefs;	
	 }
	 catch (e) { downloadextender.consoleService("blacklistenable: "+e); }
   },
   //save listen preference 
   savelisten : function(boolenable) {
     try {
       let _prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
       _prefService.setBoolPref("extensions.downloadextender.listen", !boolenable);
	 }
	 catch (e) { downloadextender.consoleService("savelisten: "+e); }
   },
   //get autodownload preference
   get autodownload() { 
     try {
       let _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.downloadextender.");
	   //gets preference if preference key is present
	   if (_prefs.getPrefType("autodownload")) { _prefs = _prefs.getBoolPref("autodownload"); }
	   else {
	     //load default preference
	     _prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	     _prefs = _prefs.getBoolPref("autodownload");
	   }
       return _prefs;	
	 }
	 catch (e) { downloadextender.consoleService("autodownload: "+e); }
   },   
   //gets the filters preference from branch
   get filters() {   
     try {
       let _filters = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.downloadextender.");
	   //checks existance of key, if found load filters
	   if (_filters.getPrefType("filters")) {	
	     _filters = JSON.parse(_filters.getCharPref("filters"));	 
	    //is preference filter key is present but there are no filters, use default filters
	     if (_filters.length == "0" || null) {
	       _filters = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	       _filters = JSON.parse(_filters.getCharPref("filters"));	 
	     }
	   }
	   else {
	     //when preference filter key is absent, use default filters	 	 
	     let _filters = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	     _filters = JSON.parse(_filters.getCharPref("filters"));	 
	   }	   
	   _filters2 = downloadextender.pref.checkdir(_filters);
       return _filters2;
       }
	 catch (e) { downloadextender.consoleService("filters: "+e); }
   },
   get blacklist() {   
   try {
       let _filters = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.downloadextender.");
	   //checks existance of key, if found load filters
	   if (_filters.getPrefType("blacklist")) {	
	     _filters = JSON.parse(_filters.getCharPref("blacklist"));	 
	    //is preference filter key is present but there are no filters, use default blacklist
	     if (_filters.length == "0" || null) {
	       _filters = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	       _filters = JSON.parse(_filters.getCharPref("blacklist"));	 
	     }
	   }
	   else {
	     //when preference filter key is absent, use default filters	 	 
	     let _filters = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	     _filters = JSON.parse(_filters.getCharPref("blacklist"));	 
	   }
       return _filters;
       }
	 catch (e) { downloadextender.consoleService("blacklist: "+e); }
   },
   //save filters
   savefilters : function(_filters) {
     try {
       let _prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
       _prefService.setCharPref("extensions.downloadextender.filters", _filters);
	 }
	 catch (e) { downloadextender.consoleService("savefilters: "+e); }
   },  
   saveblacklist : function(_filters) {
     try {
       let _prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
       _prefService.setCharPref("extensions.downloadextender.blacklist", _filters);
	 }
	 catch (e) { downloadextender.consoleService("saveblacklist: "+e); }
   },  
   //get default filters   
   get defaultfilters() { 
     try {
	   //loads default default filters	 	 
	   let _filters = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	   _filters = JSON.parse(_filters.getCharPref("filters")); 
	   _filters2 = downloadextender.pref.checkdir(_filters);
       return _filters2;	
	 }
	 catch (e) { downloadextender.consoleService("defaultfilters: "+e); }
   },   
   get defaultblacklist() { 
     try {
	   //loads default default blacklist filters	 	 
	   let _filters = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch("extensions.downloadextender.")
	   _filters = JSON.parse(_filters.getCharPref("blacklist")); 
       return _filters;	
	 }
	 catch (e) { downloadextender.consoleService("defaultblacklist: "+e); }
   }, 
   checkdir : function(_filters) {  
     try {   
       for(var i in _filters) 
	   //if there is no directory, use default download directory
	   if (_filters[i]["targetdirectory"] == "" || null)  { _filters[i]["targetdirectory"] = downloadextender.downloaddir().path; }
	   else {
	     // check if directory exists
	     let nsilocalfile = downloadextender.nsilocalfile();
		 nsilocalfile.initWithPath(unescape(_filters[i]["targetdirectory"]));
		 //use default download directory if directory doesn't exist
		 if (!nsilocalfile.exists() || !nsilocalfile.isDirectory()) { _filters[i]["targetdirectory"] = downloadextender.downloaddir().path; }		
	   }	
       return _filters;	   
	 }
	 catch (e) { downloadextender.consoleService("checkdir: "+e); }
   }     
};

let _sorted = [];
let _selectedallornot = false;
let _downloads = [];

downloadextender.download = function(aChecked, aLocalfile, aStatus, aProgress, aContentType, aSize, aID, aOrigin, aSpeed, aDmid) {
  try {    
	this._aChecked = aChecked;
	//target location on harddisc
	this._aLocalfile = aLocalfile;
	//status of download
	this._aStatus = aStatus;
	//progress of download
	this._aProgress = aProgress;
	//contenttype of download
	this._aContentType = aContentType;
	//size of download,future use?
	this._aSize = aSize;
	//id of downloadextender download
	this._aID = aID;
	//URL of download
	this._aOrigin = aOrigin;
	//download speed
	this._aSpeed = aSpeed;
	// download id of downloadmanager
	this._aDmid
  }
  catch (e) { downloadextender.consoleService("download: "+e); }
};
downloadextender.download.prototype = {
    _aLocalfile : null,
    _aChecked : null,
	_aStatus : null,
	_aProgress : null,
	_aContentType : null,
	//future use, size?
	_aSize : null,
	_aID : null,
	_aOrigin : null,
	_aCurrentPercentageBytes : null,
	_aDmid : null,
	_aSpeed : null,
	
    get id() {
	 return this._aID;
	},
	
	get speed() {
	 return this._aSpeed;
	},
	
    set speed(value) {
      this._aSpeed = value;
    },
	
	get origin() {
	 return this._aOrigin;
	},
	
	get localfile() {
	 return this._aLocalfile;
	},
	
	set localfile(value) {
      this._aLocalfile = value;
    },
	
	get checked() {
	  return this._aChecked;
	},
	
    set checked(value) {
      this._aChecked = value;
    },
	
	get contenttype() {
	 return this._aContentType;
	},
	
	get status() {
	 return this._aStatus;
	},
	
	set status(value) {
      this._aStatus = value;
    },
	
	get progress() {
	 return this._aProgress;
	},
	
    set progress(value) {
	 this._aProgress = value;
	},
	
	get size() {
	 return this._aSize;
	},	
	
	get dmid() {
	  return this._aDmid;
	},
	
	set dmid(value) {
      this._aDmid = value;
    },

};
downloadextender.download.addDownload = function(aDownload) {
  //add download to array
  try {
    _downloads.push(aDownload);
  }
  catch (e) { downloadextender.consoleService("addDownload: "+e); }
};
downloadextender.download.deleteDownload = function(aID) {
  //delete download from array
  try {
    let index = -1;
    for (var i in _downloads) { 
	  if (aID == _downloads[i].id) { index = i; }
    }
    if (index != -1	) {	_downloads.splice(index, 1); }
  }
  catch (e) { downloadextender.consoleService("deleteDownload: "+e); }
};
downloadextender.download.showDownloads = function() {
  //show downloads in window of download extender
  try {
	for (var i in _downloads) { downloadextender.mainwindow.makerow(_downloads[i]) };
  }
  catch (e) { downloadextender.consoleService("showDownloads: "+e); }
};
downloadextender.download.showSorted = function() {
  //show descending/ascending per column
  try {
    if (_sorted.length == 0) {
	  for (var y = 0; y < 6; y++) {
	    _sorted.push("ascending");
	  }
	}
	for (var i in _sorted) { 
	downloadextender.mainwindow.makesorted(i,_sorted[i]); };
  }
  catch (e) { downloadextender.consoleService("showSorted: "+e); }
};
downloadextender.download.selectionall = function() {
  //selects or deselects all checkboxes, also updates array
  try {
    for (var i in _downloads) { 
      _downloads[i].checked = !_selectedallornot;
	  downloadextender.download.updatearray(_downloads[i]);
    }
	//reverse selection for next time
    _selectedallornot = !_selectedallornot;
  }
  catch (e) { downloadextender.consoleService("selectionall: "+e); }
};
downloadextender.download.finddoublets = function(uri) {
  //finds doublets, avoids multiple downloads with same origin
  try {
    let doublet = false;
    for (var i in _downloads) { 
      if (_downloads[i].origin == uri) { doublet = true; }
    }
	return doublet;
  }
  catch (e) { downloadextender.consoleService("finddoublets: "+e); }
};
downloadextender.download.findDownload = function(aID) {
  //find a download in the download array
  try {
     let download = null;
     for (var i in _downloads) {
     if (aID == _downloads[i].id) { download = _downloads[i]; }
     }
     return download;
  }
  catch (e) { downloadextender.consoleService("findDownload: "+e); }
};
downloadextender.download.onsort = function(direction, column) {	
  try {
    if (_sorted.length == 0) {
	  for (var i = 0; i < 7; i++) {
	    _sorted.push("ascending");
	  }
	}
	
	_downloads.sort(function(a, b) {
	  if (direction == "ascending") {
	    if (column == "downloadextendername") {
		  _sorted[0] = "ascending";
          if (a.localfile.leafName < b.localfile.leafName) { return -1; }
          if (a.localfile.leafName > b.localfile.leafName) { return 1; }
          return 0;
		}
        if (column == "downloadextendertype") {
		  _sorted[1] = "ascending";
          if (a.contenttype < b.contenttype) { return -1; }
          if (a.contenttype > b.contenttype) { return 1; }
          return 0;
		}
		if (column == "downloadextenderprogress") {
		  _sorted[2] = "ascending";
          if (a.progress < b.progress) { return -1; }
          if (a.progress > b.progress) { return 1; }
          return 0;
		}
		if (column == "downloadextenderspeed") {
		  _sorted[3] = "ascending";
          if (a.speed < b.speed) { return -1; }
          if (a.speed > b.speed) { return 1; }
          return 0;
		}
		if (column == "downloadextenderstatus") {
		  _sorted[4] = "ascending";
          if (a.status < b.status) { return -1; }
          if (a.status > b.status) { return 1; }
          return 0;
		}
		if (column == "downloadextendertarget") {
		  _sorted[5] = "ascending";
          if (a.localfile.parent.path < b.localfile.parent.path) { return -1; }
          if (a.localfile.parent.path > b.localfile.parent.path) { return 1; }
          return 0;
		}
		if (column == "downloadextenderorigin") {
		  _sorted[6] = "ascending";
          if (a.origin < b.origin) { return -1; }
          if (a.origin > b.origin) { return 1; }
          return 0;
		}
	  }
	  else {
	  	if (column == "downloadextendername") {	
          _sorted[0] = "decending";	
	      if (a.localfile.leafName > b.localfile.leafName) { return -1; }
          if (a.localfile.leafName < b.localfile.leafName) { return 1; }
          return 0;
		}
		if (column == "downloadextendertype") {
		  _sorted[1] = "decending";
          if (a.contenttype > b.contenttype) { return -1; }
          if (a.contenttype < b.contenttype) { return 1; }
          return 0;
		}
		if (column == "downloadextenderprogress") {
		  _sorted[2] = "decending";
          if (a.progress > b.progress) { return -1; }
          if (a.progress < b.progress) { return 1; }
          return 0;
		}
		if (column == "downloadextenderspeed") {
		  _sorted[3] = "decending";
          if (a.speed > b.speed) { return -1; }
          if (a.speed < b.speed) { return 1; }
          return 0;
		}
		if (column == "downloadextenderstatus") {
		  _sorted[4] = "decending";
          if (a.status > b.status) { return -1; }
          if (a.status < b.status) { return 1; }
          return 0;
		}
		if (column == "downloadextendertarget") {
		  _sorted[5] = "decending";
          if (a.localfile.parent.path > b.localfile.parent.path) { return -1; }
          if (a.localfile.parent.path < b.localfile.parent.path) { return 1; }
          return 0;
		}
		if (column == "downloadextenderorigin") {
		  _sorted[6] = "decending";
          if (a.origin > b.origin) { return -1; }
          if (a.origin < b.origin) { return 1; }
          return 0;
		}
	  }
    }	
	);
  }
  catch (e) { downloadextender.consoleService("onsort: "+e); }
};
downloadextender.download.updatearray = function(aDownload) {
  //updates array and displays it if possible
  try {
    for (var i in _downloads) {
      if (_downloads[i].id == aDownload.id) {
	    _downloads[i] = aDownload;
        //update main window of download extender when it's active	
        if (downloadextender.mainwindow != null) { downloadextender.mainwindow.updaterow(aDownload); }		
      }	  
	} 
  }
  catch (e) { downloadextender.consoleService("updatearray: "+e); }
};






